const WebSocket = require('ws');
const http = require('http');

const server = http.createServer();
const wss = new WebSocket.Server({ server });

console.log('🚀 WebRTC信令服务器启动中...');

wss.on('connection', (ws) => {
    const clientId = Math.random().toString(36).substring(7);
    console.log(`✅ 新客户端连接: ${clientId}`);
    
    // 发送欢迎消息
    ws.send(JSON.stringify({
        type: 'welcome',
        clientId: clientId,
        message: '连接到信令服务器'
    }));

    ws.on('message', (message) => {
        const data = JSON.parse(message.toString());
        console.log(`📨 从 ${clientId} 收到: ${data.type}`);
        
        // 广播给所有其他客户端
        wss.clients.forEach((client) => {
            if (client !== ws && client.readyState === WebSocket.OPEN) {
                client.send(JSON.stringify(data));
            }
        });
    });
    
    ws.on('close', () => {
        console.log(`❌ 客户端断开: ${clientId}`);
    });

    ws.on('error', (error) => {
        console.log(`⚠️ 客户端 ${clientId} 错误:`, error);
    });
});

const PORT = 8080;
server.listen(PORT, '0.0.0.0', () => {
    console.log(`✅ 信令服务器运行在: ws://0.0.0.0:${PORT}`);
    console.log(`📱 网页访问地址: http://你的IP:8081/webrtc-signaling-only.html`);
});

// 优雅关闭
process.on('SIGINT', () => {
    console.log('\n🛑 关闭信令服务器...');
    wss.close(() => {
        console.log('信令服务器已关闭');
        process.exit(0);
    });
});